#include "rs485.h"

static const char *TAG = "RS485";

#include "esp_log.h"
#include "esp_err.h"
#include <string.h>
void rs485_init(void) {
    esp_err_t ret;  // 用于存储函数返回值

    // 配置 UART
    uart_config_t uart_config = {
        .baud_rate = RS485_BAUD_RATE,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_DEFAULT,
    };

    // 安装 UART 驱动
    ret = uart_driver_install(RS485_UART_PORT, RS485_BUF_SIZE * 2, 0, 0, NULL, 0);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to install UART driver: %s", esp_err_to_name(ret));
        return;
    }

    // 配置 UART 参数
    ret = uart_param_config(RS485_UART_PORT, &uart_config);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to configure UART parameters: %s", esp_err_to_name(ret));
        return;
    }

    // 设置 UART 引脚
    ret = uart_set_pin(RS485_UART_PORT, RS485_TX_PIN, RS485_RX_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to set UART pins: %s", esp_err_to_name(ret));
        return;
    }

    // 如果所有步骤成功，打印初始化成功信息
    ESP_LOGI(TAG, "RS485 initialized successfully");
}


// 发送数据
void rs485_send(const uint8_t *data, size_t len) {
    // 发送数据
    uart_write_bytes(RS485_UART_PORT, (const char *)data, len);

    // 等待数据发送完成
    uart_wait_tx_done(RS485_UART_PORT, pdMS_TO_TICKS(100));

    ESP_LOGI(TAG, "Sent %d bytes", len);
}


// 发送字符串
void rs485_send_string(const char *str) {
    if (str == NULL) {
        ESP_LOGE(TAG, "Error: NULL string provided");
        return;
    }

    size_t len = strlen(str);  // 获取字符串长度
    rs485_send((const uint8_t *)str, len);  // 调用现有的发送函数
    ESP_LOGI(TAG, "Sent string: \"%s\" (%d bytes)", str, len);
}

// 接收数据
int rs485_receive(uint8_t *buf, size_t buf_size, uint32_t timeout_ms) {
    int len = uart_read_bytes(RS485_UART_PORT, buf, buf_size, pdMS_TO_TICKS(timeout_ms));
    if (len > 0) {
        ESP_LOGI(TAG, "Received %d bytes", len);
    }
    return len;
}